package com.jd.utils;

import com.jd.domain.Content;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
@Component
public class HtmlParseUtils {

    public List<Content> parseJD(String keyword) throws IOException {
        //获取网页https://search.jd.com/Search?keyword=java
        //前提联网
        String url="https://search.jd.com/Search?keyword="+keyword;
        List<Content> contents = new ArrayList<>();
        Document document = Jsoup.parse(new URL(url), 30000);
        Element element = document.getElementById("J_goodsList");
        Elements li = element.getElementsByTag("li");
        for (Element el:li){
            String img = el.getElementsByTag("img").eq(0).attr("data-lazy-img");
            String price = el.getElementsByClass("p-price").eq(0).text();
            String name = el.getElementsByClass("p-name").eq(0).select("em").text();
            Content content = new Content(img, name, price);
            contents.add(content);
            System.out.println("=====================");
            System.out.println("商品名:" +" "+name);
            System.out.println("商品价格:" +" "+price);
            System.out.println("商品图片:" +" "+"https:"+img);
        }
        return contents;
    }

}
